#! /bin/sh
#set -x
_usage () {
	echo "usage : $0 --install-dir [directory]"
	exit 1
}

_get_dir () {
	my_label=$1
	my_var=$2
	
	chk_value=1
	while [ $chk_value = 1 ] ; do
		echo "$my_label : \c"
		read my_value
		if [ ! -d $my_value ] ; then
			echo "$my_value : repertoire inexistant !"
		else
			chk_value=0
			my_value=$(echo $my_value| sed 's#/$##g')
			eval $2=$my_value
		fi
	done
}

_make_conf_file () {
	_get_dir "Rertoire Source" source_dir
	_get_dir "Repertoire Tvshow" tvshows_dir
	_get_dir "Repertoire Film" movies_dir  
	
	#USER  NAME
	my_chk_id=1
	while [ $my_chk_id = 1 ] ; do
		echo "User name: \c"
		read id_user
		$( grep -q "^$id_user:" /etc/passwd) ; CR=$?    
		if [ $CR = 0 ] ; then
			my_chk_id=0
		else
			echo "$id_user : compte inexistant !"
		fi
	done
	
	# GROUP NAME
	my_chk_id=1
	while [ $my_chk_id = 1 ] ; do
		echo "Group name: \c"
		read id_group
		$( grep -q "^$id_group:" /etc/group) ; CR=$?
		if [ $CR = 0 ] ; then
			my_chk_id=0
		else
			echo "$id_group : group inexistant !"
		fi
	done
	
	# MAILERS
	echo "Mailers (laisser vide si non souhaité) : \c"
	read mailers

cat > $conf_file << EOF
install_dir=$install_dir
source_dir=$source_dir
tvshows_dir=$tvshows_dir
movies_dir=$movies_dir
support_file="$support_file"
db_file=$db_file
hach_file=$hach_file
err_file=$err_file
id_user=$id_user
id_group=$id_group
mailers=$mailers
regexp="$regexp"
EOF

}


_install ()
{
	[ ! -d $install_dir ] && mkdir -p $install_dir

	_make_conf_file
	
	[ ! -f $db_file ] && touch $db_file
	[ ! -f $hach_file ] && touch $hach_file
	[ ! -f $err_file ] && touch $err_file
	
	sed "s#sed_install_dir#"$install_dir"#g" $(dirname $0)/$main_file > $install_dir/$main_file
	
	chmod +x $install_dir/$main_file
	/bin/chown -R ${id_user}:${id_group} $install_dir
}


################
# MAIN PROGRAM #
################
[ "$1" != "--install-dir" ] && _usage
[ x"$2" = "x" ] && _usage

current_id=$(whoami)
[ "$current_id" != "root" ] && echo 'login root' && exit 2

# VARIABLE
install_dir=$(echo $2| sed 's#/$##g')
main_file=TR_sortmyfile.sh
conf_file=$install_dir/TRsmf.conf
db_file=$install_dir/TRsmf.db
hach_file=$install_dir/TRsmfTvShow.hach
err_file=$install_dir/TRsmf.err

support_file=".avi,.mkv,.mp4,.srt"
regexp="[Ss][0-9]\+[-,._]\?[Ee][0-9]\+ [0-9]\+x[0-9]\+"

_install

exit 0

